import {
  reqUpdateCheckedByid,
  reqDeleteGoodsById,
  reqShopCartList
} from '@/api'

const state = {
  //购物车数据列表
  shopCartList: []
}
const mutations = {
  GETSHOPCARTLIST(state, shopCartList) {
    state.shopCartList = shopCartList
  }
}
const actions = {
  //获取购物车数据列表
  async getShopCartList({ commit }) {
    let result = await reqShopCartList()
    if (result.code == 200) {
      commit('GETSHOPCARTLIST', result.data)
    }
  },
  //删除商品数据
  async deleteGoodsById({ commit }, skuId) {
    let result = await reqDeleteGoodsById(skuId)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  //修改购物车中商品的选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedByid(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  //删除所有选中商品
  deleteAllChecked({ getters, dispatch }) {
    let PromiseAll = []
    getters.cartInfoList.cartInfoList.forEach((element) => {
      let promise =
        element.isChecked == 1 ? dispatch('deleteGoodsById', element.skuId) : ''
      PromiseAll.push(promise)
    })
    return Promise.all(PromiseAll)
  },
  //全选按钮的响应事件
  updateCheckedAll({ dispatch, getters }, isChecked) {
    let PromiseAll = []
    getters.cartInfoList.cartInfoList.forEach((element) => {
      let promise =
        element.isChecked != isChecked
          ? dispatch('updateCheckedById', { skuId: element.skuId, isChecked })
          : ''
      PromiseAll.push(promise)
    })
    return Promise.all(PromiseAll)
  }
}
const getters = {
  //购物车数据
  cartInfoList(state) {
    return state.shopCartList[0] || []
  }
}
export default {
  state,
  mutations,
  actions,
  getters
}
